#ifndef _GNU_SOURCE
#define _GNU_SOURCE     1
#endif

#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <assert.h>
#include <stdio.h>
#include <unistd.h>
#include <string.h>
#include <stdlib.h>
#include <poll.h>
#include <fcntl.h>
#include <errno.h>
#include <signal.h>

#define USER_LIMIT   5              /* 最大用户数量 */
#define BUFFER_SIZE  64             /* 读缓冲区的大小 */
#define FD_LIMIT     65535          /* 文件描述符数量限制 */

volatile int sockfd = -1;

void sig_func(int sig_no) 
{
    if (sig_no == SIGINT || sig_no == SIGTERM) {
        printf("terminate application\n");

        if (sockfd >= 0) close(sockfd);
        _exit(1);
    }
}

/* 客户数据：客户端socket地址，待写到客户端的数据的位置，从客户端读入的数据 */
struct client_data {
    struct sockaddr_in address;
    char *write_buf;
    char buf[BUFFER_SIZE];
};

int setnonblocking(int fd)
{
    int old_opt = fcntl(fd, F_GETFL);
    int new_opt = old_opt | O_NONBLOCK;
    fcntl(fd, F_SETFL, new_opt);
    return old_opt;
}

int main(int argc, char *argv[])
{
    if (argc <= 2) {
        printf("usage: %s ip_address port_number\n", argv[0]);
        return 1;
    }

    printf("hello, chatroom server\n");

    signal(SIGINT, sig_func);
    signal(SIGTERM, sig_func);

    const char *ip = argv[1];
    int port = atoi(argv[2]);

    printf("server ip address: %s, port: %d\n", ip, port);

    int ret = 0;
    struct sockaddr_in servaddr;
    bzero(&servaddr, sizeof(servaddr));
    servaddr.sin_family = AF_INET;
    inet_pton(AF_INET, ip, &servaddr.sin_addr);
    servaddr.sin_port = htons(port);

    int listenfd = socket(AF_INET, SOCK_STREAM, 0);
    assert(listenfd != -1);

    ret = bind(listenfd, (struct sockaddr *)&servaddr, sizeof(servaddr));
    assert(ret != -1);

    ret = listen(listenfd, 5);
    assert(ret != -1);

    sockfd = listenfd;

    printf("server build listenfd %d\n", listenfd);

    /* 创建user数组，分配FD_LIMIT个client_data对象。可以预期：每个可能的socket连接都可以获得一个这样的对象，并且socket的值可以直接用来索引（作为数组下标）socket连接对应的client_data对象，这是将socket和客户数据关联的简单而高效的  方式 */
    struct client_data* users = new client_data[FD_LIMIT];
    struct pollfd fds[USER_LIMIT + 1];
    int user_counter = 0;

    printf("support max number of user (FD_LIMIT) is %d\n", FD_LIMIT);
    if (users == NULL) {
        fprintf(stderr, "out-of-memory error\n");
        exit(1);
    }

    for (int i = 1; i <= USER_LIMIT; ++i) {
        fds[i].fd = -1;
        fds[i].events = 0;
    }

    fds[0].fd = listenfd;
    fds[0].events = POLLIN | POLLERR;
    //fds[0].revents = 0;
    
    printf("ready to entery while-loop\n");

    while (1) {
        ret = poll(fds, user_counter + 1, -1);
        if (ret < 0) {
            printf("poll failure\n");
            break;
        }

        for (int i = 0; i < user_counter + 1; ++i) {
            if ((fds[i].fd == listenfd) && (fds[i].revents & POLLIN)) { /* 连接就绪 */
                printf("receive connection request\n");
                struct sockaddr_in cliaddr;
                socklen_t clilen = sizeof(cliaddr);
                int connfd = accept(listenfd, (struct sockaddr *)&cliaddr, &clilen);
                if (connfd < 0) {
                    printf("errno is: %d\n", errno);
                    continue;
                }

                /* 如果请求太多，则关闭新到的连接 */
                if (user_counter >= USER_LIMIT) {
                    const char *info = "too many users\n";
                    printf("%s", info);
                    send(connfd, info, strlen(info), 0);
                    close(connfd);
                    continue;
                }

                /* 对于新连接，同时修改fds和users数组。users[connfd]对应于新连接文件描述符connfd的客户数据 */
                user_counter++;
                users[connfd].address = cliaddr;

                setnonblocking(connfd);
                fds[user_counter].fd = connfd;
                /* 设置poll针对每个文件描述符监听的事件
                POLLIN: there is data to read; 
                POLLRDHUP: 
                (Linux 2.6)Peer closed connection, or shut down writing half of connection;
                POLLERR: Error condition(output only)
                */
                fds[user_counter].events = POLLIN | POLLRDHUP | POLLERR;
                fds[user_counter].revents = 0;
                printf("comes a new user, now have %d users\n", user_counter);

            }
            else if(fds[i].revents & POLLERR) { /* error for connection fds[i].fd */
                printf("get an error from %d\n", fds[i].fd);
                char errors[100];
                memset(errors, '\0', sizeof(errors));
                socklen_t length = sizeof(errors);
                /* get and clear socket error */
                if (getsockopt(fds[i].fd, SOL_SOCKET, SO_ERROR, &errors, &length) < 0) {
                    printf("get socket option failed\n");
                }

                continue;
            }
            else if (fds[i].revents & POLLRDHUP) { /* peer shut down or close */
                /* 如果客户端关闭连接，则服务器也关闭对应的连接，并将用户总数-1 */
                users[fds[i].fd] = users[fds[user_counter].fd];
                close(fds[i].fd);
                fds[i] = fds[user_counter];
                i--; /* 当前用户关闭了连接 */
                user_counter--; /* 已连接用户数-1 */
                printf("a client left\n");
            }
            else if (fds[i].revents & POLLIN) {/* user send data to server */
                /* 如果客户端有数据写入 */
                int connfd = fds[i].fd;
                memset(users[connfd].buf, '\0', BUFFER_SIZE);
                ret = recv(connfd, users[connfd].buf, BUFFER_SIZE - 1, 0); /* recv user data */
                printf("get %d bytes of client data %s from %d\n", ret, users[connfd].buf, connfd);
                if (ret < 0) {
                    /* 如果读操作出错，则关闭连接 */
                    if (errno != EAGAIN) {
                        close(connfd);
                        users[fds[i].fd] = users[fds[user_counter].fd];
                        fds[i] = fds[user_counter];
                        i--;
                        user_counter--;
                    }
                
                }
                else if (ret == 0) {
                    /* 如果对端shutdown连接，此种情形与监听POLLRDHUP事件重叠，无需单独再处理  */ 
                    /* shutdown(fds[i].fd); */
                }
                else { /* receive user data, then send it to other users */
                    /* 如果接收到客户数据，则通知其他socket连接准备写数据 */
                    for (int j = 1; j <= user_counter; ++j) {
                        if (fds[j].fd == connfd) continue;

                        fds[j].events &= ~POLLIN;
                        fds[j].events |= POLLOUT;
                        users[fds[j].fd].write_buf = users[connfd].buf;
                    }
                }
            }
            else if (fds[i].revents & POLLOUT) { /* done with writing data to other user */
                int connfd = fds[i].fd;
                if (!users[connfd].write_buf) continue;

                ret = send(connfd, users[connfd].write_buf, strlen(users[connfd].write_buf), 0);
                users[connfd].write_buf = NULL;

                /* 写完数据后需要重新注册fds[i]上的可读事件 */
                fds[i].events |= ~POLLOUT;
                fds[i].events |= POLLIN;
            }
        }
    }

    delete[] users;
    close(listenfd);
    return 0;
}


